شماره مستند: TECH-AZD-1405-002
نسخه: ۱.۰
تاریخ تهیه: آذر ۱۴۰۵
طبقه‌بندی: فنی - داخلی
TECHNICAL DOCUMENTATION

اندپوینت‌های مدیریت گیت و ورک‌آیتم‌ها در Azure DevOps

راهنمای جامع پیاده‌سازی با C# - مدل‌های ورودی و خروجی

توسعه‌دهنده گرامی،
این مستند فنی، مرجع کاملی از تمامی اندپوینت‌های REST API مربوط به مدیریت مخازن Git و مدیریت Work Item‌ها (ایشوها) در Azure DevOps Server / Azure DevOps Services ارائه می‌دهد. هر اندپوینت به همراه متد HTTP، URL، مدل‌های ورودی (Request) و خروجی (Response) و نمونه کد C# تشریح شده است. نسخه API مورد استفاده: 7.1 می‌باشد.
۱

پیش‌نیازها و احراز هویت

Prerequisites & Authentication

قبل از استفاده از هر اندپوینت، باید احراز هویت و ساختار پایه را تنظیم کنید:

🔑 ساختار پایه URL:
https://dev.azure.com/{organization}/{project}/_apis/...

نمونه کد C# - تنظیم HttpClient با PAT

using System.Net.Http.Headers; using System.Text; public class AzureDevOpsClient : IDisposable { private readonly HttpClient _httpClient; private readonly string _baseUrl; public AzureDevOpsClient(string organization, string project, string pat) { _baseUrl = $"https://dev.azure.com/{organization}/{project}"; _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String( Encoding.ASCII.GetBytes($":{pat}"))); _httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } public void Dispose() => _httpClient?.Dispose(); }
Git Repos
API
مدیریت مخازن، برنچ‌ها و سیاست‌ها
Work Items
API
مدیریت ایشوها، روابط و کوئری‌ها
API
7.1
نسخه مورد استفاده در این مستند
۲

مدیریت مخازن گیت (Git Repositories)

Git Repositories Management Endpoints

در این بخش، تمامی اندپوینت‌های مربوط به مدیریت مخازن گیت در Azure DevOps ارائه شده است:

GET دریافت لیست مخازن

GET {baseUrl}/_apis/git/repositories?api-version=7.1

دریافت لیست تمام مخازن در یک پروژه. پارامترهای اختیاری: includeAllUrls, includeHidden, includeLinks

مدل خروجی (Response)
public class GitRepositoryListResponse { public int Count { get; set; } public List<GitRepository> Value { get; set; } } public class GitRepository { public Guid Id { get; set; } public string Name { get; set; } public string Url { get; set; } public ProjectReference Project { get; set; } public string DefaultBranch { get; set; } public long Size { get; set; } public string RemoteUrl { get; set; } public string SshUrl { get; set; } public string WebUrl { get; set; } public bool IsDisabled { get; set; } public bool IsInMaintenance { get; set; } } public class ProjectReference { public Guid Id { get; set; } public string Name { get; set; } public string Url { get; set; } public string State { get; set; } public string Visibility { get; set; } }
نمونه کد C#
public async Task<GitRepositoryListResponse> GetRepositoriesAsync() { var response = await _httpClient.GetAsync( $"{_baseUrl}/_apis/git/repositories?api-version=7.1"); response.EnsureSuccessStatusCode(); return await response.Content .ReadAsAsync<GitRepositoryListResponse>(); }

GET دریافت جزئیات یک مخزن

GET {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1

دریافت اطلاعات یک مخزن خاص با استفاده از ID یا نام مخزن. پارامترهای اختیاری: includeAllUrls, includeHidden, includeLinks

پارامترهای ورودی
پارامترنوعاجباریتوضیح
repositoryIdstring / Guidبلهشناسه یا نام مخزن
includeAllUrlsboolخیرشامل تمام آدرس‌های دسترسی
includeHiddenboolخیرشامل مخازن مخفی
includeLinksboolخیرشامل لینک‌های مرتبط
مدل خروجی (Response)
// همان مدل GitRepository در بالا public async Task<GitRepository> GetRepositoryAsync(string repositoryId) { var response = await _httpClient.GetAsync( $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<GitRepository>(); }

POST ایجاد مخزن جدید

POST {baseUrl}/_apis/git/repositories?api-version=7.1
مدل ورودی (Request Body)
public class CreateGitRepositoryRequest { public string Name { get; set; } public ProjectReference Project { get; set; } public GitRepositoryRef ParentRepository { get; set; } // اختیاری - برای fork } public class GitRepositoryRef { public Guid Id { get; set; } public string Name { get; set; } }
مدل خروجی (Response) - همان GitRepository
public async Task<GitRepository> CreateRepositoryAsync(string name) { var request = new CreateGitRepositoryRequest { Name = name, Project = new ProjectReference { Name = _projectName } }; var content = new StringContent( JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync( $"{_baseUrl}/_apis/git/repositories?api-version=7.1", content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<GitRepository>(); }

PATCH به‌روزرسانی مخزن

PATCH {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1

تغییر نام، تغییر برنچ پیش‌فرض، غیرفعال‌سازی یا فعال‌سازی مخزن

مدل ورودی (Request Body)
public class UpdateGitRepositoryRequest { public string Name { get; set; } public string DefaultBranch { get; set; } // مثال: "refs/heads/main" public bool? IsDisabled { get; set; } public bool? IsInMaintenance { get; set; } }
نمونه کد C#
public async Task<GitRepository> UpdateRepositoryAsync( string repositoryId, UpdateGitRepositoryRequest request) { var content = new StringContent( JsonSerializer.Serialize(request), Encoding.UTF8, "application/json"); var httpRequest = new HttpRequestMessage( HttpMethod.Patch, $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1") { Content = content }; var response = await _httpClient.SendAsync(httpRequest); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<GitRepository>(); }

DELETE حذف مخزن

DELETE {baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1
نمونه کد C#
public async Task DeleteRepositoryAsync(string repositoryId) { var response = await _httpClient.DeleteAsync( $"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); response.EnsureSuccessStatusCode(); // Response: 204 No Content }
⚠️ هشدار: حذف مخزن غیرقابل بازگشت است. تمام تاریخچه کامیت‌ها، برنچ‌ها و تگ‌ها حذف خواهند شد.

GET دریافت آمار مخزن

GET {baseUrl}/_apis/git/repositories/{repositoryId}/stats?api-version=7.1
مدل خروجی (Response)
public class GitRepositoryStats { public GitRepositoryStatsCommitCount CommitCount { get; set; } public GitRepositoryStatsBranches Branches { get; set; } public GitRepositoryStatsPullRequests PullRequests { get; set; } } public class GitRepositoryStatsCommitCount { public int Total { get; set; } } public class GitRepositoryStatsBranches { public int Count { get; set; } }
۳

مدیریت برنچ‌ها و Refs در گیت

Git Branches & Refs Management

GET دریافت لیست برنچ‌ها

GET {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1

پارامترهای اختیاری: filter (مثلاً "heads/"), filterContains, includeStatuses, includeMyBranches, latestStatusesOnly, top, skip

مدل خروجی (Response)
public class GitRefListResponse { public int Count { get; set; } public List<GitRef> Value { get; set; } } public class GitRef { public string Name { get; set; } // "refs/heads/main" public string ObjectId { get; set; } // SHA of latest commit public string Creator { get; set; } public string Url { get; set; } public List<GitStatus> Statuses { get; set; } public bool IsLockedBy { get; set; } }

GET دریافت آمار برنچ‌ها

GET {baseUrl}/_apis/git/repositories/{repositoryId}/stats/branches?api-version=7.1

پارامتر اختیاری: name (نام برنچ برای فیلتر)

مدل خروجی (Response)
public class GitBranchStatsListResponse { public int Count { get; set; } public List<GitBranchStats> Value { get; set; } } public class GitBranchStats { public string Name { get; set; } public int AheadCount { get; set; } public int BehindCount { get; set; } public GitCommitRef Commit { get; set; } public bool IsBaseVersion { get; set; } } public class GitCommitRef { public string CommitId { get; set; } public string Comment { get; set; } public DateTime Committer { get; set; } public GitUserDate Author { get; set; } public List<string> Parents { get; set; } } public class GitUserDate { public string Name { get; set; } public string Email { get; set; } public DateTime Date { get; set; } }

POST ایجاد برنچ جدید

POST {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1
مدل ورودی (Request Body)
public class GitRefUpdate { public string Name { get; set; } // "refs/heads/new-branch" public string NewObjectId { get; set; } // SHA commit to point to public string OldObjectId { get; set; } // برای ایجاد: "0000000000000000000000000000000000000000" } // آرایه‌ای از GitRefUpdate ارسال می‌شود
مدل خروجی (Response)
public class GitRefUpdateResult { public string Name { get; set; } public string NewObjectId { get; set; } public string OldObjectId { get; set; } public bool IsLocked { get; set; } public string UpdateStatus { get; set; } // "succeeded", "rejected" public string RepositoryId { get; set; } }
نمونه کد C#
public async Task<GitRefUpdateResult> CreateBranchAsync( string repositoryId, string branchName, string sourceCommitId) { var refUpdates = new[] { new GitRefUpdate { Name = $"refs/heads/{branchName}", NewObjectId = sourceCommitId, OldObjectId = "0000000000000000000000000000000000000000" } }; var content = new StringContent( JsonSerializer.Serialize(refUpdates), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync( $"{_baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1", content); response.EnsureSuccessStatusCode(); var results = await response.Content.ReadAsAsync<List<GitRefUpdateResult>>(); return results.FirstOrDefault(); }

POST حذف برنچ (با استفاده از Refs Update)

POST {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1
مدل ورودی (حذف برنچ)
// برای حذف، NewObjectId را صفر قرار دهید var refUpdates = new[] { new GitRefUpdate { Name = $"refs/heads/{branchName}", NewObjectId = "0000000000000000000000000000000000000000", OldObjectId = currentCommitId // SHA فعلی برنچ } };

PATCH قفل/باز کردن برنچ

PATCH {baseUrl}/_apis/git/repositories/{repositoryId}/refs?api-version=7.1&filter=heads/{branchName}
مدل ورودی (Request Body)
public class GitRefUpdateLock { public bool IsLocked { get; set; } }

GET دریافت سیاست‌های برنچ

GET {baseUrl}/_apis/policy/configurations?api-version=7.1

دریافت تمام سیاست‌های تعریف شده (شامل سیاست‌های برنچ). پارامتر اختیاری: scope

مدل خروجی (Response)
public class PolicyConfigurationListResponse { public int Count { get; set; } public List<PolicyConfiguration> Value { get; set; } } public class PolicyConfiguration { public int Id { get; set; } public PolicyType Type { get; set; } public bool IsEnabled { get; set; } public bool IsBlocking { get; set; } public bool IsDeleted { get; set; } public object Settings { get; set; } // JSON - بسته به نوع سیاست public IdentityRef CreatedBy { get; set; } public DateTime CreatedDate { get; set; } } public class PolicyType { public Guid Id { get; set; } public string DisplayName { get; set; } }

POST ایجاد سیاست برنچ

POST {baseUrl}/_apis/policy/configurations?api-version=7.1
مدل ورودی (نمونه: سیاست حداقل تعداد بازبینی)
public class CreatePolicyConfigurationRequest { public bool IsEnabled { get; set; } public bool IsBlocking { get; set; } public PolicyTypeRef Type { get; set; } public BranchPolicySettings Settings { get; set; } } public class PolicyTypeRef { public Guid Id { get; set; } // Minimum number of reviewers: "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd" // Build validation: "0609b952-1397-4640-95ec-e00a01b2c241" } public class BranchPolicySettings { public List<PolicyScope> Scope { get; set; } public int MinimumApproverCount { get; set; } public int CreatorVoteCountBehaviour { get; set; } public bool AllowDownvotes { get; set; } public bool ResetOnSourcePush { get; set; } } public class PolicyScope { public string RepositoryId { get; set; } public string RefName { get; set; } // "refs/heads/main" public string MatchKind { get; set; } // "Exact", "Prefix" }
۴

مدیریت آیتم‌ها، کامیت‌ها و پول‌ریکوئست‌ها در گیت

Git Items, Commits & Pull Requests

GET دریافت آیتم‌های مخزن (فایل‌ها و پوشه‌ها)

GET {baseUrl}/_apis/git/repositories/{repositoryId}/items?api-version=7.1

پارامترها: path, recursionLevel (None, OneLevel, Full), includeContentMetadata, latestProcessedChange, download, includeContent, versionDescriptor.version, versionDescriptor.versionType

مدل خروجی (Response)
public class GitItemListResponse { public int Count { get; set; } public List<GitItem> Value { get; set; } } public class GitItem { public string ObjectId { get; set; } public GitObjectType GitObjectType { get; set; } // "blob", "tree", "commit" public VersionControlProjectInfo CommitOrBranch { get; set; } public DateTime Date { get; set; } public string Path { get; set; } public string Url { get; set; } public string Content { get; set; } // اگر includeContent=true public string IsFolder { get; set; } }

GET دریافت لیست کامیت‌ها

GET {baseUrl}/_apis/git/repositories/{repositoryId}/commits?api-version=7.1

پارامترها: searchCriteria.itemVersion.version, searchCriteria.compareVersion.version, searchCriteria.fromDate, searchCriteria.toDate, searchCriteria.itemPath, searchCriteria.author, searchCriteria.$top, searchCriteria.$skip, searchCriteria.includeWorkItems, searchCriteria.includeUser, searchCriteria.includeStatuses, searchCriteria.historyMode

مدل خروجی (Response)
public class GitCommitListResponse { public int Count { get; set; } public List<GitCommitRef> Value { get; set; } } // GitCommitRef قبلاً تعریف شده + فیلدهای اضافی: public class GitCommitRefExtended { public string CommitId { get; set; } public string Comment { get; set; } public bool CommentTruncated { get; set; } public GitUserDate Author { get; set; } public GitUserDate Committer { get; set; } public List<string> Parents { get; set; } public List<string> WorkItems { get; set; } public string Url { get; set; } public GitChangeCounts ChangeCounts { get; set; } } public class GitChangeCounts { public int Add { get; set; } public int Edit { get; set; } public int Delete { get; set; } }

GET دریافت لیست پول‌ریکوئست‌ها

GET {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests?api-version=7.1

پارامترها: searchCriteria.status (active, completed, abandoned, all), searchCriteria.creatorId, searchCriteria.reviewerId, searchCriteria.sourceRefName, searchCriteria.targetRefName, searchCriteria.includeLinks, $top, $skip

مدل خروجی (Response)
public class GitPullRequestListResponse { public int Count { get; set; } public List<GitPullRequest> Value { get; set; } } public class GitPullRequest { public int PullRequestId { get; set; } public int CodeReviewId { get; set; } public string Status { get; set; } // "active", "completed", "abandoned" public IdentityRef CreatedBy { get; set; } public DateTime CreationDate { get; set; } public DateTime? ClosedDate { get; set; } public string Title { get; set; } public string Description { get; set; } public string SourceRefName { get; set; } public string TargetRefName { get; set; } public string MergeStatus { get; set; } public bool SupportsIterations { get; set; } public GitRepository Repository { get; set; } public string Url { get; set; } }

POST ایجاد پول‌ریکوئست جدید

POST {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests?api-version=7.1
مدل ورودی (Request Body)
public class CreatePullRequestRequest { public string SourceRefName { get; set; } // "refs/heads/feature-branch" public string TargetRefName { get; set; } // "refs/heads/main" public string Title { get; set; } public string Description { get; set; } public bool IsDraft { get; set; } public List<IdentityRef> Reviewers { get; set; } public List<WorkItemRef> WorkItemReferences { get; set; } } public class IdentityRef { public string Id { get; set; } public string DisplayName { get; set; } public string UniqueName { get; set; } }

PATCH تکمیل (Merge) پول‌ریکوئست

PATCH {baseUrl}/_apis/git/repositories/{repositoryId}/pullRequests/{pullRequestId}?api-version=7.1
مدل ورودی (Request Body)
public class CompletePullRequestRequest { public string Status { get; set; } // "completed" public GitPullRequestCompletionOptions CompletionOptions { get; set; } public string LastMergeSourceCommit { get; set; } } public class GitPullRequestCompletionOptions { public bool DeleteSourceBranch { get; set; } public string MergeCommitMessage { get; set; } public bool SquashMerge { get; set; } public bool AutoCompleteSetBy { get; set; } public bool BypassPolicy { get; set; } public string TransitionWorkItemsTo { get; set; } }
۵

مدیریت ورک‌آیتم‌ها (ایشوها)

Work Items Management Endpoints

در این بخش، تمامی اندپوینت‌های مربوط به مدیریت Work Item‌ها (معادل ایشوها) در Azure DevOps ارائه شده است. این شامل ایجاد، ویرایش، حذف، کوئری، روابط و کامنت‌ها می‌باشد.

POST ایجاد ورک‌آیتم جدید

POST {baseUrl}/_apis/wit/workitems/${workItemType}?api-version=7.1

مقدار workItemType می‌تواند: Bug, Task, User Story, Feature, Epic, Issue باشد. پارامترهای اختیاری: validateOnly, bypassRules, suppressNotifications, expand

مدل ورودی (Request Body) - JSON Patch
// Content-Type: application/json-patch+json public class JsonPatchDocument : List<JsonPatchOperation> { } public class JsonPatchOperation { public string Op { get; set; } // "add", "remove", "replace", "move", "copy", "test" public string Path { get; set; } // "/fields/System.Title" public object Value { get; set; } public string From { get; set; } // برای move و copy }
نمونه کد C# - ایجاد Bug
public async Task<WorkItem> CreateBugAsync( string title, string description, string priority) { var patchDocument = new JsonPatchDocument { new JsonPatchOperation { Op = "add", Path = "/fields/System.Title", Value = title }, new JsonPatchOperation { Op = "add", Path = "/fields/System.Description", Value = description }, new JsonPatchOperation { Op = "add", Path = "/fields/Microsoft.VSTS.Common.Priority", Value = priority // "1", "2", "3", "4" }, new JsonPatchOperation { Op = "add", Path = "/fields/System.Tags", Value = "backend; critical" } }; var content = new StringContent( JsonSerializer.Serialize(patchDocument), Encoding.UTF8, "application/json-patch+json"); var response = await _httpClient.PostAsync( $"{_baseUrl}/_apis/wit/workitems/$Bug?api-version=7.1", content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<WorkItem>(); }
مدل خروجی (Response)
public class WorkItem { public int Id { get; set; } public int Rev { get; set; } public Dictionary<string, object> Fields { get; set; } public WorkItemRelations Relations { get; set; } public Dictionary<string, object> Links { get; set; } public string Url { get; set; } } // فیلدهای رایج در Dictionary: // "System.Id", "System.Title", "System.State", "System.WorkItemType" // "System.AssignedTo", "System.CreatedBy", "System.CreatedDate" // "System.Description", "System.Tags", "System.AreaPath" // "Microsoft.VSTS.Common.Priority", "Microsoft.VSTS.Common.Severity" // "Microsoft.VSTS.Scheduling.StoryPoints", "Microsoft.VSTS.Common.State"

GET دریافت یک ورک‌آیتم

GET {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1

پارامترهای اختیاری: $expand (relations, fields, all), fields (لیست فیلدها با کاما جدا شده), asOf, expand

پارامترهای ورودی
پارامترنوعاجباریتوضیح
workItemIdintبلهشناسه ورک‌آیتم
$expandstringخیرrelations, fields, all
fieldsstringخیرلیست فیلدهای درخواستی (کاما جدا شده)
asOfDateTimeخیردریافت وضعیت در تاریخ خاص
نمونه کد C#
public async Task<WorkItem> GetWorkItemAsync( int workItemId, string expand = "all") { var response = await _httpClient.GetAsync( $"{_baseUrl}/_apis/wit/workitems/{workItemId}?$expand={expand}&api-version=7.1"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<WorkItem>(); }

GET دریافت چند ورک‌آیتم همزمان

GET {baseUrl}/_apis/wit/workitems?ids={ids}&api-version=7.1

پارامترها: ids (لیست شناسه‌ها با کاما جدا شده، حداکثر ۲۰۰), $expand, fields, asOf, errorPolicy

مدل خروجی (Response)
public class WorkItemListResponse { public int Count { get; set; } public List<WorkItem> Value { get; set; } }

PATCH به‌روزرسانی ورک‌آیتم

PATCH {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1

پارامترهای اختیاری: validateOnly, bypassRules, suppressNotifications, $expand

مدل ورودی (Request Body) - JSON Patch
// Content-Type: application/json-patch+json public async Task<WorkItem> UpdateWorkItemAsync( int workItemId, Dictionary<string, object> fieldsToUpdate) { var patchDocument = new JsonPatchDocument(); foreach (var field in fieldsToUpdate) { patchDocument.Add(new JsonPatchOperation { Op = "add", // یا "replace" Path = $"/fields/{field.Key}", Value = field.Value }); } var content = new StringContent( JsonSerializer.Serialize(patchDocument), Encoding.UTF8, "application/json-patch+json"); var httpRequest = new HttpRequestMessage( HttpMethod.Patch, $"{_baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1") { Content = content }; var response = await _httpClient.SendAsync(httpRequest); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<WorkItem>(); } // مثال استفاده: var updated = await UpdateWorkItemAsync(123, new Dictionary<string, object> { { "System.State", "Resolved" }, { "Microsoft.VSTS.Common.ResolvedReason", "Fixed" }, { "System.AssignedTo", "user@example.com" } });

DELETE حذف ورک‌آیتم

DELETE {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1

پارامتر اختیاری: destroy (حذف دائمی بدون امکان بازیابی), suppressNotifications

نمونه کد C#
public async Task<WorkItemDelete> DeleteWorkItemAsync( int workItemId, bool destroy = false) { var url = $"{_baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1"; if (destroy) url += "&destroy=true"; var response = await _httpClient.DeleteAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<WorkItemDelete>(); } public class WorkItemDelete { public int Id { get; set; } public int Code { get; set; } public bool Deleted { get; set; } public string Name { get; set; } public string Type { get; set; } public string Project { get; set; } }

PATCH مدیریت روابط ورک‌آیتم (لینک‌ها)

PATCH {baseUrl}/_apis/wit/workitems/{workItemId}?api-version=7.1
مدل ورودی - افزودن رابطه
// افزودن لینک بین دو ورک‌آیتم var patchDocument = new JsonPatchDocument { new JsonPatchOperation { Op = "add", Path = "/relations/-", Value = new { rel = "System.LinkTypes.Related", url = $"{_baseUrl}/_apis/wit/workItems/{targetWorkItemId}", attributes = new { comment = "Linked related work item" } } } }; // انواع رایج روابط (rel): // "System.LinkTypes.Related" - مرتبط // "System.LinkTypes.Hierarchy-Forward" - فرزند // "System.LinkTypes.Hierarchy-Reverse" - والد // "System.LinkTypes.Dependency-Forward" - وابستگی (پس از) // "System.LinkTypes.Dependency-Reverse" - وابستگی (قبل از) // "ArtifactLink" - لینک به آرتیفکت (کامیت، PR و...) // "ExternalLink" - لینک خارجی // "Hyperlink" - هایپرلینک
مدل رابطه در خروجی
public class WorkItemRelations { public List<WorkItemRelation> Relations { get; set; } } public class WorkItemRelation { public string Rel { get; set; } public string Url { get; set; } public Dictionary<string, object> Attributes { get; set; } }

POST افزودن کامنت به ورک‌آیتم

POST {baseUrl}/_apis/wit/workitems/{workItemId}/comments?api-version=7.1
مدل ورودی (Request Body)
public class WorkItemCommentCreateRequest { public string Text { get; set; } // متن کامنت } // مثال: var commentRequest = new WorkItemCommentCreateRequest { Text = "این مشکل در نسخه 2.1 برطرف شد. لطفاً تأیید کنید." };
مدل خروجی (Response)
public class WorkItemComment { public int Id { get; set; } public int WorkItemId { get; set; } public int Version { get; set; } public string Text { get; set; } public IdentityRef CreatedBy { get; set; } public DateTime CreatedDate { get; set; } public IdentityRef ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } }

GET دریافت کامنت‌های ورک‌آیتم

GET {baseUrl}/_apis/wit/workitems/{workItemId}/comments?api-version=7.1

پارامترهای اختیاری: $top, $skip, order (asc, desc), expand (renderedText)

مدل خروجی (Response)
public class WorkItemCommentsListResponse { public int TotalCount { get; set; } public int Count { get; set; } public int FromRevision { get; set; } public List<WorkItemComment> Comments { get; set; } }

PATCH ویرایش کامنت ورک‌آیتم

PATCH {baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1
مدل ورودی (Request Body)
public class WorkItemCommentUpdateRequest { public string Text { get; set; } }

DELETE حذف کامنت ورک‌آیتم

DELETE {baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1
نمونه کد
public async Task DeleteCommentAsync(int workItemId, int commentId) { var response = await _httpClient.DeleteAsync( $"{_baseUrl}/_apis/wit/workitems/{workItemId}/comments/{commentId}?api-version=7.1"); response.EnsureSuccessStatusCode(); // Response: 204 No Content }
۶

کوئری‌های پیشرفته (WIQL) و فیلدهای ورک‌آیتم

WIQL Queries & Work Item Fields

POST اجرای کوئری WIQL

POST {baseUrl}/_apis/wit/wiql?api-version=7.1

زبان کوئری WIQL (Work Item Query Language) برای جستجوی پیشرفته ورک‌آیتم‌ها. پارامترهای اختیاری: $top, timePrecision

مدل ورودی (Request Body)
public class WiqlQueryRequest { public string Query { get; set; } } // نمونه کوئری WIQL: var query = new WiqlQueryRequest { Query = @" SELECT [System.Id], [System.Title], [System.State], [System.AssignedTo], [Microsoft.VSTS.Common.Priority] FROM WorkItems WHERE [System.WorkItemType] = 'Bug' AND [System.State] <> 'Closed' AND [System.AreaPath] UNDER 'MyProject\Backend' ORDER BY [Microsoft.VSTS.Common.Priority] ASC, [System.CreatedDate] DESC" };
مدل خروجی (Response)
public class WiqlQueryResponse { public string QueryType { get; set; } // "flat", "tree", "oneHop" public List<WorkItemReference> WorkItems { get; set; } public Dictionary<string, string> Columns { get; set; } public List<SortColumn> SortColumns { get; set; } } public class WorkItemReference { public int Id { get; set; } public string Url { get; set; } } public class SortColumn { public string Field { get; set; } public bool Descending { get; set; } }
نمونه کد C# - اجرای کوئری و دریافت نتایج کامل
public async Task<List<WorkItem>> QueryWorkItemsAsync(string wiqlQuery) { // مرحله ۱: اجرای کوئری var queryRequest = new WiqlQueryRequest { Query = wiqlQuery }; var queryContent = new StringContent( JsonSerializer.Serialize(queryRequest), Encoding.UTF8, "application/json"); var queryResponse = await _httpClient.PostAsync( $"{_baseUrl}/_apis/wit/wiql?api-version=7.1", queryContent); queryResponse.EnsureSuccessStatusCode(); var queryResult = await queryResponse.Content.ReadAsAsync<WiqlQueryResponse>(); // مرحله ۲: دریافت جزئیات ورک‌آیتم‌ها (حداکثر ۲۰۰ در هر درخواست) var workItemIds = queryResult.WorkItems.Select(w => w.Id).ToList(); var workItems = new List<WorkItem>(); for (int i = 0; i < workItemIds.Count; i += 200) { var batch = workItemIds.Skip(i).Take(200); var ids = string.Join(",", batch); var response = await _httpClient.GetAsync( $"{_baseUrl}/_apis/wit/workitems?ids={ids}&$expand=all&api-version=7.1"); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsAsync<WorkItemListResponse>(); workItems.AddRange(result.Value); } return workItems; }

GET دریافت انواع ورک‌آیتم

GET {baseUrl}/_apis/wit/workitemtypes?api-version=7.1
مدل خروجی (Response)
public class WorkItemTypeListResponse { public int Count { get; set; } public List<WorkItemType> Value { get; set; } } public class WorkItemType { public string Name { get; set; } // "Bug", "Task", "User Story" public string ReferenceName { get; set; } public string Description { get; set; } public string Color { get; set; } public string Icon { get; set; } public bool IsDisabled { get; set; } public List<WorkItemTypeStateInfo> States { get; set; } public Dictionary<string, string> XmlEncodedFieldStates { get; set; } } public class WorkItemTypeStateInfo { public string Name { get; set; } // "New", "Active", "Resolved", "Closed" public string Color { get; set; } public string Category { get; set; } // "Proposed", "InProgress", "Resolved", "Completed" }

GET دریافت فیلدهای ورک‌آیتم

GET {baseUrl}/_apis/wit/fields?api-version=7.1
مدل خروجی (Response)
public class WorkItemFieldListResponse { public int Count { get; set; } public List<WorkItemField> Value { get; set; } } public class WorkItemField { public string Name { get; set; } public string ReferenceName { get; set; } // "System.Title" public string Type { get; set; } // "string", "integer", "dateTime", "boolean", "html" public bool ReadOnly { get; set; } public bool IsIdentity { get; set; } public bool IsPicklist { get; set; } public string Usage { get; set; } // "workItem", "tree", "extension" public string Description { get; set; } public List<string> SupportedOperations { get; set; } }

GET دریافت تاریخچه تغییرات ورک‌آیتم

GET {baseUrl}/_apis/wit/workitems/{workItemId}/revisions?api-version=7.1

پارامترهای اختیاری: $top, $skip, $expand (fields, relations)

مدل خروجی (Response)
public class WorkItemRevisionListResponse { public int Count { get; set; } public List<WorkItemRevision> Value { get; set; } } public class WorkItemRevision { public int Id { get; set; } public int Rev { get; set; } public Dictionary<string, object> Fields { get; set; } public WorkItemRelations Relations { get; set; } public string Url { get; set; } }

GET دریافت آپدیت‌های ورک‌آیتم

GET {baseUrl}/_apis/wit/workitems/{workItemId}/updates?api-version=7.1

پارامترهای اختیاری: $top, $skip, $expand. تفاوت با Revisions: هر آپدیت شامل فیلدهای تغییر یافته است.

مدل خروجی (Response)
public class WorkItemUpdateListResponse { public int Count { get; set; } public List<WorkItemUpdate> Value { get; set; } } public class WorkItemUpdate { public int Id { get; set; } public int WorkItemId { get; set; } public int Rev { get; set; } public IdentityRef RevisedBy { get; set; } public DateTime RevisedDate { get; set; } public Dictionary<string, WorkItemFieldUpdate> Fields { get; set; } public WorkItemRelationUpdates Relations { get; set; } public string Url { get; set; } } public class WorkItemFieldUpdate { public object OldValue { get; set; } public object NewValue { get; set; } } public class WorkItemRelationUpdates { public List<WorkItemRelation> Added { get; set; } public List<WorkItemRelation> Removed { get; set; } public List<WorkItemRelation> Updated { get; set; } }

GET دریافت ورک‌آیتم‌های حذف شده (Recycle Bin)

GET {baseUrl}/_apis/wit/recyclebin?api-version=7.1

پارامترهای اختیاری: $top, $skip, project

مدل خروجی (Response)
public class WorkItemDeleteListResponse { public int Count { get; set; } public List<WorkItemDeleteReference> Value { get; set; } } public class WorkItemDeleteReference { public int Id { get; set; } public string Name { get; set; } public string Type { get; set; } public string Project { get; set; } public bool Deleted { get; set; } public IdentityRef DeletedBy { get; set; } public DateTime DeletedDate { get; set; } public string Code { get; set; } public string Message { get; set; } }

PATCH بازیابی ورک‌آیتم حذف شده

PATCH {baseUrl}/_apis/wit/recyclebin/{workItemId}?api-version=7.1
مدل ورودی (Request Body)
public class WorkItemDeleteUpdate { public bool IsDeleted { get; set; } // false برای بازیابی } // مثال: var restoreRequest = new WorkItemDeleteUpdate { IsDeleted = false };

GET دریافت تگ‌های ورک‌آیتم

GET {baseUrl}/_apis/wit/workitems/{workItemId}/tags?api-version=7.1
مدل خروجی (Response)
public class WorkItemTagListResponse { public int Count { get; set; } public List<WorkItemTag> Value { get; set; } } public class WorkItemTag { public Guid Id { get; set; } public string Name { get; set; } public string Url { get; set; } }

PUT افزودن تگ به ورک‌آیتم

PUT {baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagNameOrId}?api-version=7.1
نمونه کد C#
public async Task AddTagToWorkItemAsync(int workItemId, string tagName) { var content = new StringContent("", Encoding.UTF8, "application/json"); var response = await _httpClient.PutAsync( $"{_baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagName}?api-version=7.1", content); response.EnsureSuccessStatusCode(); }

DELETE حذف تگ از ورک‌آیتم

DELETE {baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagNameOrId}?api-version=7.1
نمونه کد C#
public async Task RemoveTagFromWorkItemAsync(int workItemId, string tagName) { var response = await _httpClient.DeleteAsync( $"{_baseUrl}/_apis/wit/workitems/{workItemId}/tags/{tagName}?api-version=7.1"); response.EnsureSuccessStatusCode(); }
۷

مدیریت پیوست‌ها (Attachments)

Work Item Attachments Management

POST آپلود پیوست

POST {baseUrl}/_apis/wit/attachments?fileName={fileName}&api-version=7.1

پارامتر اختیاری: areaPath. Content-Type باید application/octet-stream باشد.

نمونه کد C#
public async Task<AttachmentReference> UploadAttachmentAsync( byte[] fileContent, string fileName) { var content = new ByteArrayContent(fileContent); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await _httpClient.PostAsync( $"{_baseUrl}/_apis/wit/attachments?fileName={fileName}&api-version=7.1", content); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<AttachmentReference>(); } public class AttachmentReference { public Guid Id { get; set; } public string Url { get; set; } }
لینک کردن پیوست به ورک‌آیتم
// پس از آپلود، باید پیوست را به ورک‌آیتم لینک کنید var patchDocument = new JsonPatchDocument { new JsonPatchOperation { Op = "add", Path = "/relations/-", Value = new { rel = "AttachedFile", url = attachmentReference.Url, // از مرحله آپلود attributes = new { comment = "فایل گزارش خطا" } } } };

GET دریافت پیوست

GET {baseUrl}/_apis/wit/attachments/{attachmentId}?api-version=7.1

پارامتر اختیاری: download (true برای دانلود فایل)

نمونه کد C#
public async Task<byte[]> DownloadAttachmentAsync(Guid attachmentId) { var response = await _httpClient.GetAsync( $"{_baseUrl}/_apis/wit/attachments/{attachmentId}?download=true&api-version=7.1"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsByteArrayAsync(); }
۸

جدول خلاصه تمامی اندپوینت‌ها

Complete Endpoints Summary

الف) اندپوینت‌های مدیریت گیت:

عملیات متد اندپوینت توضیح
لیست مخازنGET/git/repositoriesدریافت تمام مخازن پروژه
جزئیات مخزنGET/git/repositories/{id}دریافت اطلاعات یک مخزن
ایجاد مخزنPOST/git/repositoriesایجاد مخزن جدید
ویرایش مخزنPATCH/git/repositories/{id}تغییر نام، برنچ پیش‌فرض
حذف مخزنDELETE/git/repositories/{id}حذف مخزن
آمار مخزنGET/git/repositories/{id}/statsآمار کامیت و برنچ
لیست RefsGET/git/repositories/{id}/refsلیست برنچ‌ها و تگ‌ها
ایجاد/حذف برنچPOST/git/repositories/{id}/refsایجاد یا حذف برنچ
آمار برنچGET/git/repositories/{id}/stats/branchesآمار برنچ‌ها
لیست آیتم‌هاGET/git/repositories/{id}/itemsفایل‌ها و پوشه‌ها
لیست کامیت‌هاGET/git/repositories/{id}/commitsتاریخچه کامیت‌ها
لیست PRهاGET/git/repositories/{id}/pullRequestsدریافت پول‌ریکوئست‌ها
ایجاد PRPOST/git/repositories/{id}/pullRequestsایجاد پول‌ریکوئست
تکمیل PRPATCH/git/repositories/{id}/pullRequests/{prId}Merge کردن
سیاست‌هاGET/policy/configurationsسیاست‌های برنچ
ایجاد سیاستPOST/policy/configurationsافزودن سیاست جدید

ب) اندپوینت‌های مدیریت ورک‌آیتم‌ها:

عملیات متد اندپوینت توضیح
ایجاد ورک‌آیتمPOST/wit/workitems/${type}ایجاد Bug, Task, Issue و...
دریافت ورک‌آیتمGET/wit/workitems/{id}جزئیات یک ورک‌آیتم
دریافت چندتاییGET/wit/workitems?ids=حداکثر ۲۰۰ همزمان
ویرایش ورک‌آیتمPATCH/wit/workitems/{id}با JSON Patch
حذف ورک‌آیتمDELETE/wit/workitems/{id}حذف (موقت یا دائمی)
مدیریت روابطPATCH/wit/workitems/{id}/relations/-
افزودن کامنتPOST/wit/workitems/{id}/commentsثبت نظر
لیست کامنت‌هاGET/wit/workitems/{id}/commentsدریافت نظرات
ویرایش کامنتPATCH/wit/workitems/{id}/comments/{cid}ویرایش نظر
حذف کامنتDELETE/wit/workitems/{id}/comments/{cid}حذف نظر
کوئری WIQLPOST/wit/wiqlجستجوی پیشرفته
انواع ورک‌آیتمGET/wit/workitemtypesBug, Task, Issue و...
فیلدهاGET/wit/fieldsتمام فیلدهای موجود
تاریخچه (Revisions)GET/wit/workitems/{id}/revisionsنسخه‌های قبلی
آپدیت‌هاGET/wit/workitems/{id}/updatesتغییرات فیلدها
سطل بازیافتGET/wit/recyclebinورک‌آیتم‌های حذف شده
بازیابیPATCH/wit/recyclebin/{id}بازگرداندن از حذف
لیست تگ‌هاGET/wit/workitems/{id}/tagsتگ‌های ورک‌آیتم
افزودن تگPUT/wit/workitems/{id}/tags/{tag}افزودن تگ
حذف تگDELETE/wit/workitems/{id}/tags/{tag}حذف تگ
آپلود پیوستPOST/wit/attachmentsآپلود فایل
دریافت پیوستGET/wit/attachments/{id}دانلود فایل
۹

کلاس سرویس یکپارچه C#

Complete AzureDevOps Service Implementation

در زیر یک کلاس سرویس کامل که تمام عملیات اصلی را پوشش می‌دهد ارائه شده است:

using System.Net.Http.Headers; using System.Text; using System.Text.Json; public interface IAzureDevOpsService { // Git Repository Operations Task<List<GitRepository>> GetRepositoriesAsync(); Task<GitRepository> GetRepositoryAsync(string repositoryId); Task<GitRepository> CreateRepositoryAsync(string name); Task<GitRepository> UpdateRepositoryAsync(string id, UpdateGitRepositoryRequest req); Task DeleteRepositoryAsync(string repositoryId); Task<List<GitRef>> GetBranchesAsync(string repositoryId); Task<GitRefUpdateResult> CreateBranchAsync(string repoId, string branch, string commitId); // Work Item Operations Task<WorkItem> CreateWorkItemAsync(string type, JsonPatchDocument patch); Task<WorkItem> GetWorkItemAsync(int id, string expand = "all"); Task<WorkItem> UpdateWorkItemAsync(int id, JsonPatchDocument patch); Task DeleteWorkItemAsync(int id, bool destroy = false); Task<List<WorkItem>> QueryWorkItemsAsync(string wiql); Task<WorkItemComment> AddCommentAsync(int id, string text); } public class AzureDevOpsService : IAzureDevOpsService, IDisposable { private readonly HttpClient _http; private readonly string _baseUrl; private static readonly JsonSerializerOptions _jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; public AzureDevOpsService(string org, string project, string pat) { _baseUrl = $"https://dev.azure.com/{org}/{project}"; _http = new HttpClient(); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{pat}"))); _http.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); } // === GIT REPOSITORY OPERATIONS === public async Task<List<GitRepository>> GetRepositoriesAsync() { var res = await _http.GetAsync($"{_baseUrl}/_apis/git/repositories?api-version=7.1"); res.EnsureSuccessStatusCode(); var result = await res.Content.ReadFromJsonAsync<GitRepositoryListResponse>(_jsonOptions); return result?.Value ?? new(); } public async Task<GitRepository> CreateRepositoryAsync(string name) { var body = new { name }; var res = await _http.PostAsJsonAsync($"{_baseUrl}/_apis/git/repositories?api-version=7.1", body, _jsonOptions); res.EnsureSuccessStatusCode(); return await res.Content.ReadFromJsonAsync<GitRepository>(_jsonOptions); } public async Task DeleteRepositoryAsync(string repositoryId) { var res = await _http.DeleteAsync($"{_baseUrl}/_apis/git/repositories/{repositoryId}?api-version=7.1"); res.EnsureSuccessStatusCode(); } public async Task<List<GitRef>> GetBranchesAsync(string repositoryId) { var res = await _http.GetAsync( $"{_baseUrl}/_apis/git/repositories/{repositoryId}/refs?filter=heads/&api-version=7.1"); res.EnsureSuccessStatusCode(); var result = await res.Content.ReadFromJsonAsync<GitRefListResponse>(_jsonOptions); return result?.Value ?? new(); } // === WORK ITEM OPERATIONS === public async Task<WorkItem> CreateWorkItemAsync(string type, JsonPatchDocument patch) { var content = new StringContent( JsonSerializer.Serialize(patch, _jsonOptions), Encoding.UTF8, "application/json-patch+json"); var res = await _http.PostAsync($"{_baseUrl}/_apis/wit/workitems/${type}?api-version=7.1", content); res.EnsureSuccessStatusCode(); return await res.Content.ReadFromJsonAsync<WorkItem>(_jsonOptions); } public async Task<WorkItem> UpdateWorkItemAsync(int id, JsonPatchDocument patch) { var content = new StringContent( JsonSerializer.Serialize(patch, _jsonOptions), Encoding.UTF8, "application/json-patch+json"); var request = new HttpRequestMessage(HttpMethod.Patch, $"{_baseUrl}/_apis/wit/workitems/{id}?api-version=7.1") { Content = content }; var res = await _http.SendAsync(request); res.EnsureSuccessStatusCode(); return await res.Content.ReadFromJsonAsync<WorkItem>(_jsonOptions); } public async Task<WorkItemComment> AddCommentAsync(int id, string text) { var body = new { text }; var res = await _http.PostAsJsonAsync( $"{_baseUrl}/_apis/wit/workitems/{id}/comments?api-version=7.1", body, _jsonOptions); res.EnsureSuccessStatusCode(); return await res.Content.ReadFromJsonAsync<WorkItemComment>(_jsonOptions); } public void Dispose() => _http?.Dispose(); }
✅ نکته مهم: برای استفاده از ReadFromJsonAsync و PostAsJsonAsync باید پکیج Microsoft.AspNetCore.Http.Extensions یا System.Net.Http.Json را نصب کنید.
۱۰

جمع‌بندی و نکات تکمیلی

Summary & Additional Notes

📋 خلاصه مستند

این مستند شامل ۱۶ اندپوینت مدیریت گیت و ۲۱ اندپوینت مدیریت ورک‌آیتم به همراه مدل‌های کامل ورودی/خروجی و نمونه کدهای کاربردی C# می‌باشد.

💡 نکات کلیدی:
• تمامی درخواست‌ها نیاز به احراز هویت با PAT یا OAuth دارند
• نسخه API مورد استفاده: 7.1 (سازگار با Azure DevOps Services و Server 2022+)
• برای ایجاد/ویرایش ورک‌آیتم از فرمت JSON Patch استفاده می‌شود
• حداکثر ۲۰۰ ورک‌آیتم در هر درخواست دسته‌ای قابل دریافت است
📚 منابع تکمیلی:
  • Azure DevOps REST API Reference: https://learn.microsoft.com/en-us/rest/api/azure/devops/
  • Git Repositories API: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/repositories
  • Work Items API: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work-items
  • WIQL Syntax: https://learn.microsoft.com/en-us/azure/devops/boards/queries/wiql-syntax
⚠️ محدودیت‌ها (Rate Limits):
  • Azure DevOps Services: محدودیت نرخ بر اساس سازمان و کاربر
  • حداکثر ۲۰۰ ورک‌آیتم در هر درخواست GET دسته‌ای
  • حداکثر ۱۰۰۰ نتیجه در هر کوئری WIQL
  • برای عملیات حجیم، از صفحه‌بندی ($top و $skip) استفاده کنید
این مستند فنی جهت استفاده تیم توسعه تهیه شده است. نسخه ۱.۰ | آذر ۱۴۰۵